<template>
  <div class="add-rule">
    <!-- 头部 -->
    <div class="header-box">
      <div class="left-box">
        <div class="return-box" @click="$router.go(-1)">
          <sc-icon name="iconfanhui"></sc-icon>
          <span class="return">返回</span>
        </div>
        <span class="line">|</span>
        <span class="title">{{ title }}</span>
      </div>
      <div class="btn-box">
        <el-button @click="$router.go(-1)">取消</el-button>
        <el-button type="primary" @click="submitData">保存</el-button>
      </div>
    </div>
    <!--内容-->
    <div class="content-box">
      <el-form ref="contentForm" :inline="true" :model="formInline" :rules="rule" class="demo-form-inline">
        <div class="cbox-head">
          <el-form-item label="故障代码" prop="errorCode">
            <el-input v-model="formInline.errorCode" placeholder="6位英文或数字"></el-input>
          </el-form-item>
          <el-form-item label="故障名称" prop="errorName">
            <el-input v-model="formInline.errorName" placeholder="限12个文字"></el-input>
          </el-form-item>
          <el-form-item label="报警等级" prop="grade">
            <el-select v-model="formInline.grade" placeholder="请选择报警等级">
              <el-option
                v-for="(item, index) in levelList"
                :key="'alarm_' + index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <div class="tip">
        <span>满足任何一条即可触发报警</span>
        <el-button class="t-btn" @click="addRuleDialog">新增条件</el-button>
      </div>
      <!--表单-->
      <div class="table">
        <div
          class="table-item"
          v-for="(item, index) in ruleList"
          :key="'table_' + index"
          :class="((index + 1) & 1) === 0 ? 'light' : ''"
        >
          <span class="number">{{ index + 1 }}</span>
          <div class="rule-list">
            <div class="rule-item" v-for="(rule, ruleIndex) in item.list" :key="'rule_' + ruleIndex">{{ rule }}</div>
          </div>
          <div class="action">
            <span class="act-btn" v-show="item.status === 2" @click="changeState(index)">启用</span>
            <span class="act-btn oringe" v-show="item.status === 1" @click="changeState(index)">停用</span>
            <span class="act-btn" @click="modifyDialog(index)">修改</span>
            <span class="act-btn red" @click="deleteData(index)">删除</span>
          </div>
        </div>
      </div>
      <!--故障描述-->
      <div class="err-desc">
        <span class="title">故障描述</span>
        <el-input
          type="textarea"
          v-model="formInline.errorDesc"
          :show-word-limit="true"
          maxlength="500"
          :rows="4"
          placeholder="请输入内容"
        >
        </el-input>
      </div>
      <!--设置报警规则-->
      <el-dialog
        title="设置报警条件"
        width="65%"
        :visible.sync="dialogTableVisible"
        :close-on-click-modal="false"
        :modal-append-to-body="false"
      >
        <div class="item" v-for="(item, index) in tableList" :key="'item_' + index">
          <el-form :inline="true" :model="item" class="demo-form-inline">
            <el-form-item label="变量名">
              <el-select
                style="width: 285px"
                v-model="item.vkStr"
                placeholder="请选择变量名称"
                @change="selectVar(index)"
              >
                <el-option
                  v-for="(varItem, varIndex) in varList"
                  :key="'var_' + varIndex"
                  :label="varItem.vname"
                  :value="varItem.vname + '-' + varItem.vk + '-' + varItem.vtype"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select style="width: 80px" v-model="item.compareType" @change="contrastData(index)" placeholder="">
                <template v-if="item.vtype !== 'Bool'">
                  <el-option label="=" value="=="></el-option>
                  <el-option label=">=" value=">="></el-option>
                  <el-option label="<=" value="<="></el-option>
                  <el-option label="!=" value="!="></el-option>
                  <el-option label=">" value=">"></el-option>
                  <el-option label="<" value="<"></el-option>
                </template>
                <template v-else>
                  <el-option label="=" value="=="></el-option>
                  <el-option label="!=" value="!="></el-option>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select style="width: 120px" v-model="item.compareObject">
                <el-option label="对比值" :value="1"></el-option>
                <el-option label="对比变量" :value="2"></el-option>
              </el-select>
            </el-form-item>
            <template v-if="item.compareObject === 1">
              <el-form-item prop="compareValue">
                <el-input
                  style="width: 160px"
                  type="number"
                  clearable
                  v-model="item.compareValue"
                  :min="0"
                  :max="item.vtype && item.vtype === 'Bool' ? 1 : 10000"
                  @input="validateEvent(index, 1, item.vtype && item.vtype === 'Bool' ? 1 : 10000)"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
              <el-form-item label="恢复值">
                <el-select style="width: 80px" v-model="item.recoverType" placeholder="">
                  <template v-if="item.vtype !== 'Bool'">
                    <el-option label="=" value="=="></el-option>
                    <el-option label=">=" value=">="></el-option>
                    <el-option label="<=" value="<="></el-option>
                    <el-option label="!=" value="!="></el-option>
                    <el-option label=">" value=">"></el-option>
                    <el-option label="<" value="<"></el-option>
                  </template>
                  <template v-else>
                    <el-option label="=" value="=="></el-option>
                    <el-option label="!=" value="!="></el-option>
                  </template>
                </el-select>
              </el-form-item>
              <el-form-item prop="recoverValue">
                <el-input
                  style="width: 160px"
                  v-model="item.recoverValue"
                  type="number"
                  clearable
                  :min="0"
                  :max="item.vtype && item.vtype === 'Bool' ? 1 : 10000"
                  @input="validateEvent(index, 2, item.vtype && item.vtype === 'Bool' ? 1 : 10000)"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </template>
            <template v-else>
              <el-form-item>
                <el-select
                  style="width: 261px"
                  v-model="item.ckStr"
                  placeholder="请选择变量名称"
                  @change="changeVar(index)"
                >
                  <el-option
                    v-for="(varItem, varIndex) in varList"
                    :key="'var_' + varIndex"
                    :label="varItem.vname"
                    :value="varItem.vname + '-' + varItem.vk + '-' + varItem.vtype"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="时差">
                <el-input
                  style="width: 160px"
                  type="number"
                  clearable
                  v-model="item.timeDiff"
                  placeholder="ms"
                ></el-input>
              </el-form-item>
            </template>
            <el-form-item>
              <div class="btns">
                <sc-icon
                  class="form-btn"
                  v-if="index > 0"
                  name="iconbtn-shanchu"
                  @click.native="subLine(index)"
                ></sc-icon>
                <sc-icon class="form-btn" v-if="index === 0" name="iconbtn-tianjia" @click.native="addLine"></sc-icon>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogTableVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmRule">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getModelDetail, modifyRule, createRule, getAlarmDetail } from '../../../api/rule';
export default {
  name: 'addRule',
  data() {
    const checkName = (rule, value, callback) => {
      if (/[ ]/.test(value)) {
        callback(new Error('名称不能包含空格'));
      }
      callback();
    };
    return {
      levelList: [
        // 报警等级
        { label: '一级', value: 1 },
        { label: '二级', value: 2 },
        { label: '三级', value: 3 },
        { label: '四级', value: 4 },
        { label: '五级', value: 5 }
      ],
      query: {},
      contrastRule: ['!=', '<=', '>=', '==', '<', '>'], // 对比
      title: '',
      tableList: [], // 条件list
      ruleList: [],
      varModify: -1, // 修改
      isModify: false,
      formInline: {}, // from
      dialogTableVisible: false, // 设置条件弹框
      varList: [], // 物模型变量列表
      rule: {
        errorCode: [
          { required: true, message: '请输入故障代码', trigger: 'blur' },
          { min: 6, max: 6, message: '6位英文或数字', trigger: 'blur' }
        ],
        errorName: [
          { required: true, message: '请输入故障名称', trigger: 'blur' },
          { min: 1, max: 12, message: '限12个文字', trigger: 'blur' },
          { validator: checkName, trigger: 'blur' }
        ],
        grade: [{ required: true, message: '请选择报警等级', trigger: 'blur' }]
      }
    };
  },
  mounted() {
    this.query = this.$route.query;
    this.title = this.query.title;
    if (this.query.grade) {
      this.getAlarmDetail(this.query.id);
      this.isModify = true;
    } else {
      this.isModify = false;
    }
    this.getModelDetailInfo();
  },
  beforeRouteLeave(to, from, next) {
    if (!to.query.modelId) {
      to.query.modelId = this.query.modelId;
      next();
    } else {
      next();
    }
  },
  methods: {
    // 获取物模型详情
    getModelDetailInfo() {
      getModelDetail({ id: this.query.modelId }).then(res => {
        this.varList = res.data;
      });
    },
    // 详情数据回显
    getAlarmDetail(id) {
      getAlarmDetail({ id: id }).then(res => {
        const detail = res.data;
        const rules = detail.ruleList;
        rules.forEach(item => {
          const group = item.group;
          let temp = [];
          group.forEach((groupItem, groudIndex) => {
            if (!groupItem.ckStr) {
              if (groupItem.ctype) {
                groupItem.ckStr = groupItem.cname + '-' + groupItem.ck + '-' + groupItem.ctype;
              } else {
                groupItem.ckStr = groupItem.cname + '-' + groupItem.ck + '-' + groupItem.vtype;
              }
            }
            if (!groupItem.vkStr) {
              groupItem.vkStr = groupItem.vname + '-' + groupItem.vk + '-' + groupItem.vtype;
            }
            if (groupItem.compareObject === 1) {
              temp.push(`${groupItem.vname} ${groupItem.compareType} ${groupItem.compareValue}`);
            } else {
              temp.push(`${groupItem.vname} ${groupItem.compareType} ${groupItem.cname}`);
            }
          });
          this.ruleList.push({
            list: temp,
            status: item.status,
            sourceData: group
          });
        });
        this.$nextTick(res => {
          let temp = {};
          temp.errorCode = detail.errorCode;
          temp.errorDesc = detail.errorDesc;
          temp.errorName = detail.errorName;
          temp.grade = detail.grade;
          temp.id = detail.id;
          this.formInline = temp;
        });
      });
    },
    // 添加line
    addLine() {
      this.tableList.push({ compareType: '==', compareObject: 1, recoverType: '!=', modelId: this.modelId });
    },
    // 删除line
    subLine(i) {
      this.tableList = this.tableList.filter((item, index) => index !== i);
    },
    // 删除条件
    deleteData(index) {
      this.ruleList = this.ruleList.filter((item, i) => index !== i);
    },
    // 选择变量
    selectVar(index) {
      const item = this.tableList[index];
      const param = item.vkStr.split('-');
      console.log('param', param);
      item.vk = param[1];
      item.vname = param[0];
      item.vtype = param[2];
      this.tableList[index] = item;
    },
    // 对比变量选择
    changeVar(index) {
      const item = this.tableList[index];
      const param = item.ckStr.split('-');
      item.ck = param[1];
      item.cname = param[0];
      item.ctype = param[2];
      this.tableList[index] = item;
    },
    // 新增
    addRuleDialog() {
      this.varModify = -1;
      this.tableList = [{ compareType: '==', compareObject: 1, recoverType: '!=' }];
      this.dialogTableVisible = true;
    },
    // 对比
    contrastData(index) {
      const item = this.tableList[index];
      if (item.vtype !== 'Bool') {
        const rule = ['==', '>=', '<=', '!=', '>', '<'];
        const i = rule.indexOf(item.compareType);
        item.recoverType = this.contrastRule[i];
        this.tableList[index] = item;
      } else {
        const rule = ['==', '!='];
        const compare = ['!=', '=='];
        const i = rule.indexOf(item.compareType);
        item.recoverType = compare[i];
        this.tableList[index] = item;
      }
    },
    // 确认报警规则
    confirmRule() {
      let temp = [],
        sourceData = [];
      this.tableList.forEach(item => {
        sourceData.push(item);
        if (item.compareObject === 1) {
          temp.push(`${item.vname} ${item.compareType} ${item.compareValue}`);
        } else {
          temp.push(`${item.vname} ${item.compareType} ${item.cname}`);
        }
      });
      if (this.varModify > -1) {
        this.ruleList[this.varModify] = { list: temp, status: 1, sourceData: sourceData };
      } else {
        this.ruleList.push({ list: temp, status: 1, sourceData: sourceData });
      }
      this.dialogTableVisible = false;
    },
    // 启用停用
    changeState(index) {
      const item = this.ruleList[index];
      if (item.status === 1) {
        item.status = 2;
      } else {
        item.status = 1;
      }
      this.ruleList[index] = item;
    },
    // 修改报警规则
    modifyDialog(index) {
      this.tableList = this.ruleList[index].sourceData;
      this.varModify = index;
      this.dialogTableVisible = true;
    },
    // 新增报警规则
    submitData() {
      this.$refs.contentForm.validate(res => {
        if (res) {
          let temp = [];
          this.ruleList.forEach(item => {
            const source = item.sourceData;
            source.forEach(item => {
              if (item.timeDiff) {
                item.timeDiff = parseInt(item.timeDiff);
              } else {
                item.timeDiff = 0;
              }
              if (item.compareValue) {
                item.compareValue = parseInt(item.compareValue);
              } else {
                item.compareValue = 0;
              }
              if (item.recoverValue) {
                item.recoverValue = parseInt(item.recoverValue);
              } else {
                item.recoverValue = 0;
              }
            });
            temp.push({ status: item.status, group: source });
          });
          this.formInline.errorCode = this.formInline.errorCode.toUpperCase();
          const param = Object.assign({}, this.formInline, { modelId: this.query.modelId }, { ruleList: temp });
          if (!this.isModify) {
            createRule(param).then(res => {
              this.$message({
                type: 'success',
                message: '操作成功'
              });
              this.$router.go(-1);
            });
          } else {
            modifyRule(param).then(res => {
              this.$message({
                type: 'success',
                message: '操作成功'
              });
              this.$router.go(-1);
            });
          }
        }
      });
    },
    validateValue(index) {
      const item = this.tableList[index];
      const rule = ['==', '>=', '<=', '!=', '>', '<'];
      const compareRule = ['!=', '<=', '>=', '==', '<', '>'];
      const boolRule = ['==', '!='];
      const boolCompareRule = ['!=', '=='];
      const vtype = item.vtype;
      const compare = item.compareValue ? parseInt(item.compareValue) : 0;
      const recover = item.recoverValue ? parseInt(item.recoverValue) : 0;
      if (item.compareObject === 1) {
        if (compare && recover) {
          let index = -1;
          if (vtype === 'Bool') {
            index = boolRule.indexOf(item.compareType);
          } else {
            index = rule.indexOf(item.compareType);
          }
          const recoverFlag = vtype === 'Bool' ? boolCompareRule[index] : compareRule[index];
          if (recoverFlag !== item.recoverType) {
            this.$message({
              message: '恢复值或对比值的运算应相反，将自动修改',
              type: 'warning'
            });
            item.recoverType = recoverFlag;
          } else {
            if (item.compareType !== '==' && item.compareType !== '!=') {
              let flag = false;
              if (compare > recover) {
                if (item.compareType !== '>=' && item.compareType !== ' >') {
                  flag = true;
                  item.compareType = '>=';
                }
                if (item.recoverType !== '<=' && item.recoverType !== '<') {
                  flag = true;
                  item.recoverType = item.compareType === '>=' ? '<=' : '<';
                }
              }
              if (compare === recover) {
                if (item.compareType !== '>' && item.compareType !== '<') {
                  flag = true;
                  item.compareType = '>;';
                }
                if (item.recoverType !== '<' && item.recoverType !== '>') {
                  flag = true;
                  item.recoverType = item.compareType === '>' ? '<' : '>';
                }
              }
              if (compare < recover) {
                if (item.compareType !== '<=' && item.compareType !== '<') {
                  flag = true;
                  item.compareType = '<=';
                }
                if (item.recoverType !== '>=' && item.recoverType !== '>') {
                  flag = true;
                  item.recoverType = item.compareType === '<=' ? '>=' : '>';
                }
              }
              if (flag) {
                this.$message({
                  message: '恢复值与对比值的比值不正确,将自动修改',
                  type: 'warning'
                });
              }
            }
          }
        }
      }
    },
    // 验证
    validateEvent(index, type, max) {
      const item = this.tableList[index];
      if (type === 1) {
        const val = parseInt(item.compareValue);
        if (val > max) {
          item.compareValue = max.toString();
        } else {
          item.compareValue = Math.round(val).toString();
        }
      } else {
        const val = parseInt(item.recoverValue);
        if (val > max) {
          item.recoverValue = max.toString();
        } else {
          item.recoverValue = Math.round(val).toString();
        }
      }
      this.tableList[index] = item;
      this.validateValue(index);
    }
  }
};
</script>
<style lang="scss" scoped>
.red {
  color: red !important;
}
.btns {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 36px;
  .form-btn {
    font-size: 30px;
    color: #85aeff;
    cursor: pointer;
  }
}
.light {
  background: #fafafa;
}
.oringe {
  color: #ffb039 !important;
}

// 头部
.header-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 70px;
  padding: 0 20px;
  border-bottom: 1px solid #ebeef5;
  .left-box {
    display: flex;
    align-items: center;
    .return-box {
      cursor: pointer;
      .return {
        color: #303133;
        font-size: 14px;
        margin-left: 3px;
      }
    }
    .line {
      margin: 0 12px;
      color: #c0c4cc;
    }
    .title {
      font-size: 18px;
      color: #606266;
    }
  }
}
.content-box {
  .cbox-head {
    padding: 20px 20px 0px 20px;
    width: 80%;
    display: flex;
    justify-content: space-between;
  }
  .tip {
    display: flex;
    justify-content: flex-end;
    padding-right: 20px;
    align-items: center;
    color: #909399;
    font-size: 14px;
    padding-bottom: 20px;
    .t-btn {
      margin-left: 10px;
      color: #3378ff;
    }
  }
  .table {
    width: 100%;
    display: flex;
    flex-direction: column;
    padding: 0px 20px 20px 20px;
    max-height: 327px;
    overflow: auto;
    .table-item {
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-top: 1px solid #ebeef5;
      padding: 10px;
      .number {
        padding-left: 10px;
        color: #606266;
        font-size: 14px;
        flex: 1;
      }
      .rule-list {
        flex: 8;
        display: flex;
        align-items: center;
        overflow: auto;
        text-overflow: ellipsis;
        white-space: nowrap;
        .rule-item {
          color: #67c23a;
          font-size: 12px;
          background: #f0f9eb;
          border: 1px solid #d9f0ce;
          box-sizing: border-box;
          border-radius: 4px;
          padding: 10px;
          margin-left: 10px;
        }
      }
      .action {
        flex: 2;
        display: flex;
        .act-btn {
          font-size: 14px;
          color: #3378ff;
          margin-left: 30px;
          cursor: pointer;
        }
      }
    }
  }
  .err-desc {
    display: flex;
    align-items: center;
    padding: 20px;
    .title {
      width: 78px;
      font-size: 14px;
      color: #606266;
    }
  }
}
</style>
